import React, { Suspense } from 'react';
import ReactDOM from 'react-dom';
import {
  BrowserRouter as Router, Route,Link
} from 'react-router-dom';

function lazy(load) {
  return class extends React.Component {
    state = { InnerComponent: null }
    componentDidMount() {
      load().then(result => {
        this.setState({ InnerComponent: result.default || result });
      });
    }
    render() {
      const { InnerComponent } = this.state;
      return InnerComponent ? <InnerComponent /> : null;
    }
  }
}


/*
Suspense lets components “wait” for something before rendering.
Today, Suspense only supports one use case: loading components dynamically with React.lazy.
In the future, it will support other use cases like data fetching.

Note that rendering lazy components requires that there’s a <React.Suspense> component higher in the rendering tree.
This is how you specify a loading indicator.

Note that lazy components can be deep inside the Suspense tree — it doesn’t have to wrap every one of them.

Note:
Using React.lazywith dynamic import requires Promises to be available in the JS environment. This requires a polyfill on IE11 and below.

Note:
React.lazy() and <React.Suspense> are not yet supported by ReactDOMServer. This is a known limitation that will be resolved in the future.(v17.0.1)
*/
const LazyHome = React.lazy(() => import(/* webpackChunkName: "Home" */'./components/Home'));
console.log('LazyHome:',LazyHome);
const LazyLogin = React.lazy(() => import(/* webpackChunkName: "Login" */'./components/Login'));
console.log('LazyLogin:',LazyLogin);

function Loading() {
  return <div>加载中......</div>
}

function SuspenseHome() {
  return (
    <Suspense fallback={<Loading />}>
      <LazyHome />
    </Suspense>
  )
}
function SuspenseLogin() {
  return (
    <Suspense fallback={<Loading />}>
      <LazyLogin />
    </Suspense>
  )
}
//webpack chunkFilename
ReactDOM.render(
  <Router>
    <div>
      <ul>
        <li><Link to="/">Home</Link></li>
        <li><Link to="/login">User</Link></li>
      </ul>
      <Route exact path="/" component={SuspenseHome} />
      <Route path="/login" component={SuspenseLogin} />
    </div>
  </Router>,
  document.getElementById('root')
);
